package com.defaultlist.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import com.cardefaultcond.model.CarDefaultCondService;
import com.cardefaultcond.model.CarDefaultCondVO;
import com.defaultlist.model.*;

public class DefaultListServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {		
		
		req.setCharacterEncoding("UTF-8");
		String action = req.getParameter("action");
		HttpSession session = req.getSession();
		
		if ("goto_update_cond".equals(action)) {
			RequestDispatcher failureView = req
					.getRequestDispatcher("/defaultlist/update_cond.jsp");
			failureView.forward(req, res);
		}
		
		if ("update_cond".equals(action)) {
			List<String> errorMsgs = new LinkedList<String>();
			req.setAttribute("errorMsgs", errorMsgs);
			
			String requestURL = req.getParameter("requestURL");			
			String member_id = req.getParameter("member_id");
			List<DefaultCondListVO> list = new ArrayList<DefaultCondListVO>();

			CarDefaultCondService cdcSvc = new CarDefaultCondService();
			List<CarDefaultCondVO> cdc = cdcSvc.getAll();
			for (CarDefaultCondVO c : cdc) {
				DefaultCondListVO dcl = new DefaultCondListVO();
				dcl.setDefaultcond_id(c.getDefaultcond_id());
				dcl.setValue(Integer.valueOf(req.getParameter(c
						.getHtml_name())));
				list.add(dcl);
			}
			try {
				DefaultCondListService dclSvc = new DefaultCondListService();
				dclSvc.updateCond(list, member_id);
				RequestDispatcher failureView = req
						.getRequestDispatcher(requestURL);
				failureView.forward(req, res);
			} catch (Exception e) {
				errorMsgs.add(e.getMessage());
				RequestDispatcher failureView = req
						.getRequestDispatcher("/defaultlist/update_cond.jsp");
				failureView.forward(req, res);
			}
		}
	}
}
